package com.foreveross.proxyip.infra.db.mongo;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.proxyip.infra.utils.CacheUtils;
import com.foreveross.proxyip.infra.utils.PropertiesUtil;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

/**
 * mongo管理工具类 
 * 
 * @author fb
 */
public class MongoManager {
	
	private static Logger logger = LoggerFactory.getLogger(MongoManager.class);
	
	private static volatile MongoManager mongoManager = null;
	
	private final String mongoProperties = "jdbc/mongodb";
	
	private MongoClient mongo = null;
	
	private MongoManager () {
		Properties properties = PropertiesUtil.getProperties(mongoProperties, CacheUtils.CacheInstance.MOFANG);
		String host = properties.getProperty("mongo.host");

		try {
			mongo = new MongoClient(new ServerAddress(host), createCredentials(), createBuild().build());
		} catch (UnknownHostException e) {
			logger.error(e.getMessage(), e);
		}
	}

	public static MongoManager instance () {
		if (mongoManager == null) {
			synchronized (MongoManager.class) {
				if (mongoManager == null) {
					mongoManager = new MongoManager();
				}
			}
		}
		
		return mongoManager;
	}
	
	public MongoClient getMongoClient() {
		return mongo;
	}
	
	
	private List<MongoCredential> createCredentials() {
		Properties properties = PropertiesUtil.getProperties(mongoProperties, CacheUtils.CacheInstance.MOFANG);
		List<MongoCredential> credentials = new ArrayList<MongoCredential>();
		String database[] = properties.getProperty("mongo.database").split(",");
		String user[] = properties.getProperty("mongo.user").split(",");
		String pwd[] = properties.getProperty("mongo.pwd").split(",");

		for (int i = 0; i < database.length; i++) {
			credentials.add(MongoCredential.createMongoCRCredential(user[i].trim(), database[i].trim(), pwd[i].trim().toCharArray()));
		}
		
		return credentials;
	}
	
	private Builder createBuild() {
		Properties properties = PropertiesUtil.getProperties(mongoProperties, CacheUtils.CacheInstance.MOFANG);
		int connectTimeout = Integer.parseInt(properties.getProperty("mongo.connectTimeout", "10000").trim());
		int socketTimeout = Integer.parseInt(properties.getProperty("mongo.socketTimeout", "10000").trim());
		int threadsAllowedToBlock = Integer.parseInt(properties.getProperty("mongo.threadsAllowedToBlock", "5").trim());
		int connectionsPerHost = Integer.parseInt(properties.getProperty("mongo.connectionsPerHost", "100").trim());

		return MongoClientOptions.builder()
				.connectTimeout(connectTimeout) 								            // 连接超时，默认0无限等待
				.socketTimeout(socketTimeout) 								                // sokect超时，默认0无限等待
				.connectionsPerHost(connectionsPerHost)                                     // 最大连接数
				.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlock); 		// 线程队列数
	}
	
}
